package com.woniuxy.nio.channel.filechannel;

import com.woniuxy.nio.util.FileUtils;

import java.io.RandomAccessFile;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 使用 FileChannel 写入数据
 * <P> Date: 2022/4/3:10:42
 * <P> Description:
 */

public class FileChannelWriteDemo1 {
    public static void main(String[] args) throws Exception{
        //1.创建 FileChannel
        RandomAccessFile accessFile =
                new RandomAccessFile(FileUtils.FILE_SOURCE,"rw");
        FileChannel channel = accessFile.getChannel();

        //2.创建buffer对象
        ByteBuffer buf = ByteBuffer.allocate(1024);

        String newData = "data dasd";
        buf.clear();

        //3.写入内容
        buf.put(newData.getBytes());

        //TODO 把limit设为当前position，把position设为0，一般在从Buffer读出数据前调用
        buf.flip();

        //4.从buf中读取数据 开始写入
        while (buf.hasRemaining()){
            channel.write(buf);
        }

        channel.close();

    }
}
